package com.mediacloud.app.newsmodule.fragment.video.live;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import android.text.TextUtils;
import android.view.ViewTreeObserver.OnPreDrawListener;
import android.widget.CompoundButton;

import com.mediacloud.app.assembly.util.BitmapUtil;
import com.mediacloud.app.assembly.util.DateParse;
import com.mediacloud.app.assembly.views.RadioButtonX;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.fragment.newslist.TableCatalogItemsFragmentBase;
import com.mediacloud.app.newsmodule.model.SimpleNavigateItem;
import com.mediacloud.app.newsmodule.utils.VideoLiveProgramListInvoker;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig;
import com.mediacloud.app.model.interfaces.DataInvokeCallBack;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.model.news.LiveProgramListReciver;
import com.mediacloud.app.model.news.ProgramListItem;
import com.mediacloud.app.model.news.LiveProgramListReciver.ProgramWeekItem;

/**
 * 直播节目单
 */
public class LiveProgramTableFragment extends TableCatalogItemsFragmentBase<SimpleNavigateItem> implements DataInvokeCallBack<LiveProgramListReciver> {

    public static final String Program = "Program";
    /**
     * 选择的日期索引
     */
    protected int chooseDateIndex = 0;
    protected ArticleItem articleItem;
    VideoLiveProgramListInvoker liveProgramListInvoker;
    protected ArrayList<ProgramWeekItem> programListItems;
    public int middle = 3;
    public GetProgramData programGetHandle;
    ArrayList<Map<String, List<ProgramListItem>>> allProgramList = new ArrayList<Map<String, List<ProgramListItem>>>();

    @Override
    protected void getArgs() {
        navigateItems = new ArrayList<SimpleNavigateItem>();

        articleItem = getFragmentArguments().getParcelable("data");
        programListItems = (ArrayList<ProgramWeekItem>) getFragmentArguments().getSerializable(Program);
    }

    public void intCalender(int liveItems) {
        navigateItems.clear();
        middle = (liveItems - 1) / 2;
        String[] days = getResources().getStringArray(R.array.weekdaynames);
        for (int i = 0; i < liveItems; i++) {
            SimpleNavigateItem catalogItem = new SimpleNavigateItem();
            catalogItem.index = i;
            int tempindex = 0;
            Calendar calendar = Calendar.getInstance();
            int date = calendar.get(Calendar.DATE);
            if (i < middle) {
                tempindex = middle - i;
                calendar.set(Calendar.DATE, date - tempindex);
                calendar.get(Calendar.DAY_OF_WEEK);
                tempindex = DateParse.getWeek(calendar);
                tempindex -= 1;
                catalogItem.name = days[tempindex];
            } else if (i > middle) {
                tempindex = i - middle;
                calendar.set(Calendar.DATE, date + tempindex);
                calendar.get(Calendar.DAY_OF_WEEK);
                tempindex = DateParse.getWeek(calendar);
                tempindex -= 1;
                catalogItem.name = days[tempindex];
            } else {
                catalogItem.name = getResources().getString(R.string.today);
            }
            navigateItems.add(catalogItem);
        }

    }

    @Override
    public void initView() {
        super.initView();
        //topContainer.setBackgroundResource(R.drawable.jinghua_listdivider);
        getProgramList();
    }

    protected void getProgramList() {
        liveProgramListInvoker = new VideoLiveProgramListInvoker(this);
        //如果外面传进来的数据是空的话
        if (programListItems == null || programListItems.size() == 0)
            liveProgramListInvoker.getLiveVideoProgramList(articleItem);
    }

    /**
     * 设置日期列表
     *
     * @param programListItems
     */
    public void setDatePrograms(List<ProgramWeekItem> programListItems) {
        if(navigateItems==null)
            navigateItems=new ArrayList<>();
        navigateItems.clear();
        middle = (programListItems.size() - 1) / 2;
        for (int i = 0; i < programListItems.size(); i++) {
            SimpleNavigateItem catalogItem = new SimpleNavigateItem();
            catalogItem.index = i;
            if (i == middle) {
                catalogItem.name = getResources().getString(R.string.today);
            } else {
                catalogItem.name = programListItems.get(i).getTitle();
            }
            navigateItems.add(catalogItem);
        }
    }

    /**
     * 节目单获取失败或者没有数据
     */
    public void setDefaultProgramsList() {
        navigateItems.clear();
        middle = (13 - 1) / 2;
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat(getActivity().getString(R.string.program_date_formate));
        for (int i = 0; i < 13; i++) {
            long timeStamp = date.getTime() - (24 * 60 * 60 * 1000) * (middle - i);
            SimpleNavigateItem catalogItem = new SimpleNavigateItem();
            catalogItem.index = i;
            if (i == middle) {
                catalogItem.name = getResources().getString(R.string.today);
            } else {
                catalogItem.name = sdf.format(new Date(timeStamp));
            }
            navigateItems.add(catalogItem);
        }
    }

    public void choooseMiddle() {
        /*RadioButtonX radioButtonX = (RadioButtonX) mCatalogGroupContainer.getChildAt(middle);
        radioButtonX.setChecked(true);*/
        mCatalogItemContainer.setCurrentTab(middle);
    }

    @Override
    public void success(LiveProgramListReciver result) {
        if (getActivity() == null || requireActivity().isFinishing()||requireActivity().isDestroyed()) {
            return ;
        }
        if (result.state && result.programListItems != null) {
            if (result.programListItems.size() > 0) {
                if (result.programListItems.get(0).getTitle() == null || TextUtils.isEmpty(result.programListItems.get(0).getTitle())) {
                    //默认一周7天
                    intCalender(7);
                } else {
                    setDatePrograms(result.programListItems);
                }
            } else {
                setDefaultProgramsList();
            }

            super.setTabLayoutData();
            choooseMiddle();
            int index = 0;
            for (LiveProgramListReciver.ProgramWeekItem programList : result.programListItems) {
                LiveProgramItemFragment fragment = (LiveProgramItemFragment) contentFragmentAdapter.getItem(index);
                if (fragment == null)
                    continue;
                fragment.setListData(programList.programList);
                String key = navigateItems.get(index).name;
                index++;
                LinkedHashMap<String, List<ProgramListItem>> map = new LinkedHashMap<String, List<ProgramListItem>>();
                map.put(key, programList.programList);
                allProgramList.add(map);
            }

            mRootView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    lastSelectIndex = middle;
                    mCatalogItemContainer.setCurrentTab(middle);
                }
            }, 1000);
            if (programGetHandle != null)
                programGetHandle.getProgram(allProgramList);
            else if(allProgramList!=null)
                allProgramList.clear();
        } else {
            fault(null);
        }
    }

    @Override
    public void fault(Object data) {
        if (getActivity() == null || requireActivity().isFinishing()||requireActivity().isDestroyed()) {
            return ;
        }
        setDefaultProgramsList();
        super.setTabLayoutData();
/*        RadioButtonX radioButtonX = (RadioButtonX) mCatalogGroupContainer.getChildAt(middle);
        radioButtonX.setChecked(true);*/
        mCatalogItemContainer.setCurrentTab(middle);
        for (int index = 0; index < contentFragmentAdapter.getCount(); index++) {
            LiveProgramItemFragment fragment = (LiveProgramItemFragment) contentFragmentAdapter.getItem(index);
            fragment.setListData(null);
        }
        mRootView.postDelayed(new Runnable() {
            @Override
            public void run() {
                lastSelectIndex = middle;
                mCatalogItemContainer.setCurrentTab(middle);
            }
        }, 1000);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (liveProgramListInvoker != null)
            liveProgramListInvoker.destory();
        liveProgramListInvoker = null;
    }

    @Override
    protected void setCatalogItemContentList(FragmentManager manager, ArrayList<Fragment> list) {
        super.setCatalogItemContentList(manager, list);
        mContentViewPager.setOffscreenPageLimit(list.size());
    }

    @Override
    public Fragment getViewContentFragment(SimpleNavigateItem catalogItem) {
        LiveProgramItemFragment fragment = new LiveProgramItemFragment();
        fragment.liveTableIndex = catalogItem.index;
        Bundle bundle = new Bundle();
        bundle.putParcelable("data", catalogItem);
        if (programListItems != null && programListItems.size() == navigateItems.size()) {
            List<ProgramListItem> programList = programListItems.get(catalogItem.index).programList;
            if (programList == null)
                programList = new ArrayList<ProgramListItem>();
            bundle.putSerializable(Program, (Serializable) programList);
        }
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public int getLayoutResID() {
        return R.layout.aappfactory_livedetail_fragment;
    }
    @Override
    protected RadioButtonX createRadioButtonItem(SimpleNavigateItem catalogItem) {
        final RadioButtonX radioButtonX = super.createRadioButtonItem(catalogItem);
        radioButtonX.setText(catalogItem.name);
        int textColor = getResources().getColor(R.color.light_black_color);
        radioButtonX.setTextColor(textColor);
        radioButtonX.uncheckedTextColor = textColor;
        int color = Color.parseColor(AppFactoryGlobalConfig.getAppServerConfigInfo(getActivity()).getColor());
        radioButtonX.checkedTextColor = color;
        radioButtonX.drawableType = RadioButtonX.bottom;
        radioButtonX.setTextSize(12);
        radioButtonX.getViewTreeObserver().addOnPreDrawListener(new OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                radioButtonX.getViewTreeObserver().removeOnPreDrawListener(this);
                BitmapDrawable checkedDrawableDefault = (BitmapDrawable) getResources().getDrawable(R.drawable.msgcenter_checkdrawable);
                Bitmap bitmap;
                try {
                    bitmap = BitmapUtil.zoomBitmap(checkedDrawableDefault.getBitmap(), radioButtonX.getMeasuredWidth(), checkedDrawableDefault.getBitmap().getHeight());
                } catch (Exception e) {
                    bitmap = checkedDrawableDefault.getBitmap();
                    e.printStackTrace();
                }
                BitmapDrawable checkedDrawable = new BitmapDrawable(getResources(), bitmap);
                BitmapDrawable uncheckedDrawable = new BitmapDrawable(getResources(), bitmap);
                radioButtonX.checkedDrawable = checkedDrawable;
                radioButtonX.uncheckedDrawable = uncheckedDrawable;
                radioButtonX.updateEffDrawable();
                radioButtonX.setTint(AppFactoryGlobalConfig.getAppServerConfigInfo(getActivity()).getMainColor(), Color.TRANSPARENT);
                return true;
            }
        });
        return radioButtonX;
    }

    @Override
    protected TableCatalogItemsFragmentBase<SimpleNavigateItem>.RadioButtonCheckeChangedListener getRadioButtonCheckeChangedListener(
            RadioButtonX radioButtonX, int index) {
        return new RadioButtonCheckeChangedListenerX(radioButtonX, index);
    }

    private class RadioButtonCheckeChangedListenerX extends RadioButtonCheckeChangedListener {

        public RadioButtonCheckeChangedListenerX(RadioButtonX radioButtonX,
                                                 int index) {
            super(radioButtonX, index);
        }
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            super.onCheckedChanged(buttonView, isChecked);
            if (isChecked) {
                radioButtonX.getPaint().setFakeBoldText(true);
            } else {
                radioButtonX.getPaint().setFakeBoldText(false);
            }
        }
    }

    protected void invalidateRadioButtonsPadding() {
        int margin = getResources().getDimensionPixelSize(R.dimen.appfactory_liveprogramtable_btnmargin);
        int containerWidth = topContainer.getMeasuredWidth();
        int scrollerWidth = mCatalogItemContainer.getMeasuredWidth();
        int gap = containerWidth - scrollerWidth;
        if (gap < 0)
            gap = 0;
//        mCatalogGroupContainer.invalidatePadding2(margin, gap, true);
    }

    public interface GetProgramData {
        void getProgram(List<Map<String, List<ProgramListItem>>> data);
    }

    public void selectLiveTableChild(int tableIndex, int childIndex) {
        if (contentFragmentAdapter == null || contentFragmentAdapter.getCount() == 0 || tableIndex >= contentFragmentAdapter.getCount())
            return;
        for (int i = 0; i < contentFragmentAdapter.getCount(); i++) {
            LiveProgramItemFragment fragment = (LiveProgramItemFragment) contentFragmentAdapter.getItem(i);
            if (tableIndex == i)
                fragment.liveProgramAdaptor.selectedIndex = childIndex;
            else
                fragment.liveProgramAdaptor.selectedIndex = -1;
            fragment.updateChoosePlayIndex(tableIndex);
//			fragment.updateLiveLabelDelay(childIndex);
        }

    }
    @Override
    public void onSaveInstanceState(Bundle outState) {
        if(articleItem!=null)
            outState.putParcelable("data", articleItem);
        super.onSaveInstanceState(outState);
    }
}